using RealtimeCollabGame.Application.Commands;
using RealtimeCollabGame.Application.Interfaces;

namespace RealtimeCollabGame.Application.Handlers;

public class StartGameCommandHandler
{
    private readonly IGameRepository _gameRepository;

    public StartGameCommandHandler(IGameRepository gameRepository)
    {
        _gameRepository = gameRepository;
    }

    public async Task HandleAsync(StartGameCommand command)
    {
        var game = await _gameRepository.GetByIdAsync(command.GameId);
        if (game == null)
        {
            throw new InvalidOperationException($"游戏 {command.GameId} 不存在");
        }

        // 检查是否是房主
        if (game.HostId != command.RequestedByPlayerId)
        {
            throw new InvalidOperationException("只有房主可以开始游戏");
        }

        game.StartGame();
        await _gameRepository.UpdateAsync(game);
    }
}